package tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description: 501. 二叉搜索树中的众数
 * User: Li_yizYa
 * Date: 2025/6/9
 * Time: 11:45
 */
public class Solution30 {
    /**
     * 非递归
     * @param root
     * @return
     */
    public int[] findMode2(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        TreeNode pre = null;
        List<Integer> retList = new ArrayList<>();
        int count = 0;
        int maxCount = 0;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                // 计数
                if (pre == null || pre.val != cur.val) {
                    count = 0;
                } else {
                    count++;
                }
                if (count > maxCount) {
                    maxCount = count;
                    retList.clear();
                    retList.add(cur.val);
                } else if (count == maxCount) {
                    retList.add(cur.val);
                }
                pre = cur;
                cur = cur.right;
            }
        }
        int[] ret = new int[retList.size()];
        for (int i = 0; i < retList.size(); i++) {
            ret[i] = retList.get(i);
        }
        return ret;
    }
    /**
     * 递归
     */
    List<Integer> retList = new ArrayList<>();
    int count = 0;
    int maxCount = 0;
    TreeNode pre = null;
    public int[] findMode(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        findMode1(root);
        int[] ret = new int[retList.size()];
        for (int i = 0; i < retList.size(); i++) {
            ret[i] = retList.get(i);
        }
        return ret;
    }

    private void findMode1(TreeNode root) {
        if (root == null) {
            return;
        }
        // 左
        findMode1(root.left);
        // 计数
        if (pre == null || pre.val != root.val) {
            count = 0;
        } else {
            count++;
        }
        if (count > maxCount) {
            maxCount = count;
            retList.clear();
            retList.add(root.val);
        } else if (count == maxCount) {
            retList.add(root.val);
        }
        pre = root;
        // 右
        findMode1(root.right);
    }
}
